<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isAdd ? '新增日期信息' : '修改日期信息'"
    top="80px"
    width="750px"
    :close-on-click-modal="true"
    custom-class="edit-calendar-dialog"
    :close-on-press-escape="false"
    @close="() => $emit('update:visible', false)"
  >
		<el-form
			ref="formRef"
			:model="calendarInfoForm"
			label-width="80px"
		>
			<el-form-item label="类型：" prop="calendarType" required>
				<el-select v-model="calendarInfoForm.calendarType" placeholder="请选择">
					<el-option
						v-for="item in calendarList"
						:key="item.label"
						:label="item.label"
						:value="item.label"
					/>
				</el-select>
			</el-form-item>
			<el-form-item
				label="日期："
				:rules="[
					{ required: true, message: '请选择日期', trigger: 'blur' }
				]"
				prop="date"
			>
				<el-date-picker
					v-model="calendarInfoForm.date"
					type="date"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					placeholder="选择日期"
				/>
			</el-form-item>
			<el-form-item v-show="calendarInfoForm.calendarType === '农历(阴历)'" label="是闰月：" prop="isLeap" required>
				<el-radio-group v-model="calendarInfoForm.isLeap" class="ml-4">
					<el-radio :label="true" size="large">是</el-radio>
					<el-radio :label="false" size="large">否</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="备注：">
				<el-input v-model="calendarInfoForm.remarks" clearable placeholder="请输入"></el-input>
			</el-form-item>
		</el-form>
		<div class="result-content">
			<el-button @click="compute">计算</el-button>
			<el-button @click="resultJson = ''">清除</el-button>
			<p>{{ resultJson }}</p>
		</div>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="$emit('update:visible', false)">取消</el-button>
				<el-button type="primary" @click="submit">保存</el-button>
			</span>
		</template>
  </el-dialog>
</template>

<script setup name="CalendarDialog">
import { ref, watchEffect, nextTick } from 'vue'
import { getDialogHeight } from '@/utils/utils'
import { calendar } from '@/utils/calendar'
import { addCalendar, updateCalendar } from '@/api/calendar'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const calendarList = [
	{ label: '农历(阴历)' },
	{ label: '公历(阳历)' }
]
const props = defineProps({
  isAdd: Boolean, // 是否是新增操作
	visible: Boolean, // 显示弹窗
	calendarInfoIndex: {
		type: Number,
		default: -1
	}, // 日期下标
	calendarInfo: {
		type: Object, // 日期信息记录
		default: function() {
			return {}
		}
	}
})
// eslint-disable-next-line no-unused-vars
const emit = defineEmits(['update:visible', 'updateCalendarInfo'])
const dialogVisible = ref(false) // 显示弹窗
const calendarInfoForm = ref({}) // 日期信息
const formRef = ref({})
const resultJson = ref('') // 日期信息结果 json字符串

// 监听器
watchEffect(async()=>{
	dialogVisible.value = props.visible
	if(props.visible) {
		resultJson.value = ''
		await nextTick()
		getDialogHeight('.edit-calendar-dialog', 200)
	}
	calendarInfoForm.value = {
		calendarType: '公历(阳历)',
		date: dayjs(props.calendarInfo.date || '').format('YYYY-MM-DD'),
		isLeap: false,
		remarks: props.calendarInfo.remarks || ''
	}
	// JSON.parse(JSON.stringify(props.calendarInfo))
})

// 计算日期信息
const compute = async function(isHide = false) {
	try {
		await validateForm()
	} catch (error) {
		return console.log('表单校验失败', error || '')
	}
	console.log('表单校验通过')
	let result = {}
	const date = new Date(calendarInfoForm.value.date)
	const y = date.getFullYear()
	const m = date.getMonth() + 1
	const d = date.getDate()
	if(calendarInfoForm.value.calendarType === '农历(阴历)') { // 农转公
		result = calendar.lunar2solar(y, m, d, calendarInfoForm.value.isLeap)
	} else { // 公转农
		result = calendar.solar2lunar(y, m, d)
	}
	const keyArr = ['Animal', 'IDayCn', 'IMonthCn', 'Term']
	keyArr.forEach(key=>{
		result[`${key.substr(0,1).toLocaleLowerCase() + key.substr(1)}`] = result[key] || ''
		delete result[key]
	})
	if(isHide === true) {
		return JSON.stringify(result)
	} else {
		resultJson.value = JSON.stringify(result)
	}
	console.log('result--', result)
}

// 提交/保存
const submit = async function() {
	try {
		await validateForm()
	} catch (error) {
		return console.log('表单校验失败', error || '')
	}
	try {
		let params = {}
		if(!resultJson.value) { // 没有计算预览
			const resJson = await compute(true)
			params = JSON.parse(resJson)
		} else {
			params = JSON.parse(resultJson.value)
		}
		params.remarks = calendarInfoForm.value.remarks
		let res = {}
		if(props.isAdd) { // 新增
			for (const key in params) {
				if(params[key] === null) {
					params[key] = ''
				}
			}
			res = await addCalendar(params)
			emit('updateCalendarInfo')
		} else { // 修改
			const info = { ...props.calendarInfo }
			console.log('info--------', info)
			for (const key in info) {
				if (Object.hasOwnProperty.call(params, key)) {
					info[key] = params[key]
				}
				if(info[key] === null) {
					info[key] = ''
				}
			}
			res = await updateCalendar(info)
			emit('updateCalendarInfo', info, props.calendarInfoIndex)
		}
		if(res.status === 200) {
			ElMessage.success(`${props.isAdd ? '添加' : '修改'}成功！`)
			emit('update:visible', false)
		}
	} catch (error) {
		console.log('保存 error---', error)
	}

}

// 表单校验
function validateForm() {
	return new Promise((resolve, reject) => {
		if (!formRef.value) resolve()
		formRef.value.validate((valid) => {
			if (valid) {
				resolve()
			} else {
				reject()
			}
		})
	})
}

</script>
<style lang='scss' scoped>
.edit-calendar-dialog {

}
</style>
